package cn.ekuma.data.ui.android;

import java.util.ArrayList;
import java.util.List;

import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Toast;
import cn.ekuma.android.ui.tree.TreeElement;
import cn.ekuma.data.dao.I_DataLogic;
import cn.ekuma.data.dao.bean.I_Category;

public abstract class AbstractTreeFinderActivate <T extends I_Category> extends AbstractFinderActivate{

	public AbstractTreeFinderActivate(I_DataLogic dataLogic) {
		super(dataLogic);
	}


	AbstractBaseBeanTreeAdapter listAdapter;
	BaseBeanCategorySelecter main;
	
	@Override
	public View createContentPanel() {
		main=new BaseBeanCategorySelecter<T>(this);
		listAdapter=getTreeAdapter();
		main.setAbstractBaseBeanTreeAdapter(listAdapter);
		main.setOnBaseBeanSelectedListener(this);
		return main;
	}

	public abstract AbstractBaseBeanTreeAdapter getTreeAdapter();
	
	
	protected Handler mHandler = new Handler() {  
        public void handleMessage (Message msg) {//此方法在ui线程运行   
            switch(msg.what) {  
            case MSG_SUCCESS:  
            	listAdapter.setRootNode(buildTree((List<T>) msg.obj));
                break;
            case MSG_FAILURE:  
                Toast.makeText(getApplication(), "执行出错了", Toast.LENGTH_LONG).show();  
                break;
            }  
        }  
    };
    
    
    private List<TreeElement> buildTree(List<T> beans){
    	TreeElement root=new TreeElement("根",null);
    	buildTreeForList((List<I_Category>) beans,root);
		return root.getChildren();
    }
    
    private void buildTreeForList(List<I_Category> m_aData,TreeElement parent){
		if(m_aData.isEmpty())
			return;
		List<I_Category> recapt=new ArrayList();
		TreeElement temp;
		for(I_Category c:m_aData){
			if(isChinad(parent,c)){
				temp=new TreeElement(c.getName(), (Object)c);
				parent.addChild(temp);
			}else 
				recapt.add(c);
		}
		for(int i=0;i<parent.childCount();i++)
			buildTreeForList(recapt,(TreeElement) parent.getChild(i));
	}
    
    
    private boolean isChinad(TreeElement parent,I_Category category1){
    	I_Category category=(I_Category) parent.getTag();
    	boolean isChinad=false;
		if(category==null){
			if(category1.getM_sParentID()==null)
				isChinad=true;
		}else if(category.getID().equalsIgnoreCase(category1.getM_sParentID()))
			isChinad=true;
		return  isChinad;
    }

}
